package com.canbot.u05.activity.shoppingGuide.merchandiseShoppingGuide;

import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.CompoundButton;

import com.alibaba.fastjson.JSON;
import com.canbot.u05.R;
import com.canbot.u05.activity.BaseActivityNoTitle;
import com.canbot.u05.activity.customvoice.tool.GridSpacingItemDecoration;
import com.canbot.u05.bean.JsonResponse;
import com.canbot.u05.bean.sales.ChoosePicBean;
import com.canbot.u05.network.SalesApi;
import com.canbot.u05.socket.IpMsgConst;
import com.canbot.u05.utils.DisplayUtils;
import com.canbot.u05.utils.Logger;
import com.canbot.u05.utils.ToastTools;
import com.canbot.u05.view.PicPreviewDialog;
import com.canbot.u05.widget.LoadingDialogUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

import okhttp3.OkHttpClient;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * 商品导购选择图片界面
 */
public class MerchandiseChoosePicActivity extends BaseActivityNoTitle implements View.OnClickListener, MerchandisePicAdapter.OnPhotoItemCheckedListener, MerchandisePicAdapter.OnItemClickListener {

        private static final String TAG = "MerchandiseChoosePicActivity";

        private Button btnBack, btnOk;

        private RecyclerView gridView;

        private List<ChoosePicBean> mList;

        private String picPath;

        private MerchandisePicAdapter adapter;

        private List<ChoosePicBean> selectedList;

        private List<String> editPath;

        private PicPreviewDialog picPreviewDialog;


        @Override
        protected void onCreate(Bundle savedInstanceState) {
                super.onCreate(savedInstanceState);
                setContentView(R.layout.activity_merchandise_choose_pic);

                picPath = getIntent().getStringExtra("pic");
                if (!TextUtils.isEmpty(picPath)) {
                        picPath = picPath.replace("[", "");
                        picPath = picPath.replace("]", "");
                        String[] p = picPath.split(",");
                        editPath = new ArrayList<>();
                        for (int i = 0; i < p.length; i++) {
                                editPath.add(p[i]);
                        }
                        Logger.e(TAG, "原有图片editPath= "+ editPath.toString());
                }
                mList = new ArrayList<>();
                selectedList = new ArrayList<>();
                setViews();
                initPicData();

        }

        private void setViews() {
                btnBack = (Button) findViewById(R.id.back);
                btnOk = (Button) findViewById(R.id.btn_ok);
                gridView = (RecyclerView) findViewById(R.id.gv_content);
                btnOk.setOnClickListener(this);
                btnBack.setOnClickListener(this);
        }

        private Dialog dialogLoading;

        private void initPicData() {

                dialogLoading = LoadingDialogUtils.createLoadingDialog(this, getString(R.string.loading));
                String url = "http://" + IpMsgConst.SOCKET_HOST2 + ":7755/";
                Logger.e("t", url);
                Retrofit retrofit = new Retrofit.Builder()
                        .baseUrl(url)
                        .addConverterFactory(GsonConverterFactory.create())
                        .client(setTimeOut())
                        .build();
                SalesApi salesApi = retrofit.create(SalesApi.class);
                final Call<JsonResponse> pic = salesApi.getPic("/uupic");
                pic.enqueue(new Callback<JsonResponse>() {
                        @Override
                        public void onResponse(Call<JsonResponse> call, Response<JsonResponse> response) {
                                LoadingDialogUtils.closeDialog(dialogLoading);
                                List<ChoosePicBean> list = new ArrayList<ChoosePicBean>();
                                if (response.body() != null) {
                                        JsonResponse path = response.body();
                                        Logger.e(TAG, " onResponse" + response.body());
                                        if (path != null) {

                                                if (path.getRc() == -1) {
                                                        return;
                                                }
                                                List<String> result = JSON.parseArray(path.getResult().toString(), String.class);
                                                Logger.e(TAG, "result==" + result.toString());

                                                for (int i = 0; i < result.size(); i++) {
                                                        String s = result.get(i);
                                                        Logger.e(TAG, "设置选中picPath" + picPath + "------ 服务器获取=" + s);
                                                        Logger.e(TAG, "editPath" + editPath );
                                                        ChoosePicBean choosePicBean = null;
                                                        if (editPath != null  && editPath.size() >0 ){
                                                                for (String mm : editPath){
                                                                        if (mm.contains(s) || s.contains(mm)){
                                                                                choosePicBean = new ChoosePicBean(s, true);
                                                                                break;
                                                                        }else {
                                                                                choosePicBean = new ChoosePicBean(s, false);
                                                                        }
                                                                }


                                                        }else {
                                                                 choosePicBean = new ChoosePicBean(s, false);
                                                        }
                                                        list.add(choosePicBean);
                                                }
                                                setAdapter(list);
                                        }
                                }
                        }

                        @Override
                        public void onFailure(Call<JsonResponse> call, Throwable t) {
                                Logger.e(TAG, "失败==" + t.toString());
                                LoadingDialogUtils.closeDialog(dialogLoading);
                                ToastTools.newInstance(MerchandiseChoosePicActivity.this).showText(getString(R.string.network_error));
                        }
                });

        }

        private void setAdapter(List<ChoosePicBean> list) {
                mList.addAll(list);
                gridView.setLayoutManager(new GridLayoutManager(this, 4, GridLayoutManager.VERTICAL,false));
                gridView.addItemDecoration(new GridSpacingItemDecoration(4, DisplayUtils.dip2px(this,30), false));
                adapter = new MerchandisePicAdapter(MerchandiseChoosePicActivity.this, mList, this, this);
                gridView.setAdapter(adapter);
//                adapter = new MerchandisePicAdapter(MerchandiseChoosePicActivity.this, mList, this, this);
//                gridView.setAdapter(adapter);
        }


        /**
         * 选中
         *
         * @param photoModel
         * @param buttonView
         * @param isChecked
         */
        @Override
        public void onCheckedChanged(int position,ChoosePicBean photoModel, CompoundButton buttonView, boolean isChecked) {

                if (isChecked) {
                        mList.get(position).setChecked(true);
//                        adapter.isSelected.put(position, true); // 修改map的值保存状态
                        if (selectedList.contains(photoModel)){
                                return;
                        }
                        selectedList.add(photoModel);
                        if (gridView.getScrollState() == RecyclerView.SCROLL_STATE_IDLE
                                && !gridView.isComputingLayout()) {
                                ChoosePicBean c = mList.get(position);
                                c.setChecked(true);
                                adapter.updateItem(position,c,selectedList);
                        }

                }
                else {
                        mList.get(position).setChecked(false);
                        selectedList.remove(photoModel);
                        if (gridView.getScrollState() == RecyclerView.SCROLL_STATE_IDLE
                                && !gridView.isComputingLayout()) {
                                ChoosePicBean c = mList.get(position);
                                c.setChecked(false);
                                adapter.updateItem(position,c,selectedList);
//
                        }
                }
                if (selectedList != null && selectedList.size() > 5) {
                        selectedList.remove(selectedList.size() - 1);
//                        return;
                }
                Logger.e(TAG, "selectedList选择== " + selectedList.toString());

        }

        @Override
        public void onClick(View view) {

                switch (view.getId()) {
                        case R.id.back:
                                finish();
                                overridePendingTransition(R.anim.face_zoom_enter, R.anim.face_zoom_exit);
                                break;
                        case R.id.btn_ok:
                                if (selectedList.isEmpty()) {
                                        setResult(RESULT_CANCELED);
                                }
                                else {
                                        Intent data = new Intent();
                                        Bundle bundle = new Bundle();
                                        bundle.putString("photos", JSON.toJSONString(selectedList));
                                        Logger.e(TAG, "选择的图片==" + selectedList.toString());
                                        data.putExtras(bundle);
                                        setResult(RESULT_OK, data);
                                }
                                finish();
                                overridePendingTransition(R.anim.face_zoom_enter, R.anim.face_zoom_exit);
                                break;
                }
        }

        /**
         * 点击图片
         *
         * @param position
         */
        @Override
        public void onItemClick(int position) {
                preview(mList.get(position).getImagePath());
        }

        /**
         * 预览图片
         *
         * @param path
         */
        private void preview(String path) {
                Logger.e(TAG, "预览path=" + path);
                picPreviewDialog = new PicPreviewDialog(MerchandiseChoosePicActivity.this, R.style.centerdialog, path);
                picPreviewDialog.show();
        }
        private static final int TIMEOUT = 100;//超时时间100s

        /**
         * 设置超时
         * @return
         */
        private OkHttpClient setTimeOut(){
                OkHttpClient client = new OkHttpClient.Builder()
                        .connectTimeout(TIMEOUT, TimeUnit.SECONDS)
                        .writeTimeout(TIMEOUT, TimeUnit.SECONDS)
                        .readTimeout(TIMEOUT, TimeUnit.SECONDS)
                        .build();
                return client;

        }

        @Override
        protected void onDestroy() {
                if (dialogLoading != null){
                        dialogLoading.dismiss();
                }
                super.onDestroy();
        }
}
